package com.gaotong.science.controller;

import com.gaotong.science.config.MyException;
import com.gaotong.science.util.R;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@CrossOrigin
@RequestMapping("/download")
public class DownloadFile {

    @GetMapping("/file/{name}")
    public void downloadFile(@PathVariable String name, HttpServletResponse response){
       String  path ="/root/zheng/outdata/";
        File file = new File(path+name);
        if (!file.exists()) {
            throw new MyException(201,"文件不存在");
        }
        try{
            response.setContentType("application/force-download");
//通过设置头信息给文件命名，也即是，在前端，文件流被接受完还原成原文件的时候会以你传递的文件名来命名
            response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", URLEncoder.encode(name, "utf-8")));
        }catch (Exception e){
            e.printStackTrace();
        }

        byte[] buffer = new byte[1024];
        try (FileInputStream fis = new FileInputStream(file);

             BufferedInputStream bis = new BufferedInputStream(fis)) {

            OutputStream os = response.getOutputStream();

            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
